import 'dart:async';
import 'dart:isolate';

import 'package:flutter_track/base/base_logger.dart';
import 'package:flutter_track/base/base_tracker.dart';
import 'package:flutter_track/base/tracker_message_bean.dart';
import 'package:flutter_track/tracker_isolate/tracker_worker_ffi.dart';
import 'package:flutter_track/tracker_isolate/tracker_worker_isolate.dart';

const String tag = "TrackerIsolate";

class TrackerIsolate extends BaseIsolateTracker {
  Isolate? _trackerIsolate;
  ReceivePort? _mainReceivePort;
  SendPort? _trackerSendPort;

  /// 创建一个 tracker 隔离 isolate，需要微小任务调度。
  /// 微小任务调度由外侧传入
  void _createTrackerIsolate({
    required Function(
            {required ActionMessage message, SendPort? trackerSendPort})
        handleMainMessage,
  }) {
    /// 构建接收端口
    _mainReceivePort = ReceivePort("main_receive_port");

    /// 构建工作隔离区
    /// 仅且当构建完成隔离区时，会进行listen的操作

    Isolate.spawn(TrackerWorkerIsolate.trackerActionWithPort,
            _mainReceivePort!.sendPort)
        .then((isolate) {
      _trackerIsolate = isolate;
      _mainReceivePort?.listen((message) {
        if (message is SendPort) {
          _trackerSendPort = message;
        } else if (message is ActionMessage) {
          /// 由 tracker_isolate 类进行关闭，返回到上层内容无 tracker 发送端口
          var sendPort = _trackerSendPort;
          if (message.action == SendAction.exit) {
            TrackerWorkerFFI.releaseFFI();

            /// 收到了 worker isolate 的关闭指令，关闭主接收端口，杀掉 worker isolate
            /// 向上抛发送端口为 null
            _mainReceivePort?.close();
            _trackerIsolate?.kill(priority: Isolate.immediate);
            sendPort = null;
          }
          handleMainMessage(
            message: message,
            trackerSendPort: sendPort,
          );
        } else {
          Log.info(
            tag: tag,
            message:
                "unknow message listen from mainisolate.. : $message, current isolate:${Isolate.current.debugName}",
          );
        }
      });
    }).onError((error, stackTrace) {
      Log.info(
          tag: tag,
          message:
              "create isolate error..., ${error.toString()}, stack: ${stackTrace.toString()}");
    });
  }

  @override
  void closeTracker() {
    /// 应该由 worker isolate 发起中断之后，再由 main isolate 进行最终退出
    _trackerSendPort?.send(ActionMessage(action: SendAction.exit));
  }

  @override
  void doTrack(int? baseIsolateInstructions, int? baseVm) {
    /// 向 worker isolate 发送启动微型任务信息，由 worker isolate 启动任务
    _trackerSendPort?.send(ActionMessage(
      msg: "${baseIsolateInstructions?.toString() ?? ""}#${baseVm ?? ""}",
      action: SendAction.shouldSendMicroTask,
    ));
  }

  @override
  void initTracker({
    required Function(
            {required ActionMessage message, SendPort? trackerSendPort})
        handleMainMessage,
  }) {
    TrackerWorkerFFI.setStackSaveSavePath();
    _createTrackerIsolate(handleMainMessage: handleMainMessage);
    TrackerWorkerFFI.registerSignalToMainIsolate();
  }
}
